package com.dy.yunying.biz.service.datacenter.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dy.yunying.api.constant.OsEnum;
import com.dy.yunying.api.dto.XingTuDataDTO;
import com.dy.yunying.api.entity.ChannelManageDO;
import com.dy.yunying.api.entity.WanGameChannelInfoDO;
import com.dy.yunying.api.entity.WanGameDO;
import com.dy.yunying.api.vo.XingTuDataVO;
import com.dy.yunying.biz.dao.datacenter.impl.XingTuDataDao;
import com.dy.yunying.biz.dao.manage.ChannelManageDOMapper;
import com.dy.yunying.biz.dao.manage.WanGameChannelInfoMapper;
import com.dy.yunying.biz.dao.manage.WanGameDOMapper;
import com.dy.yunying.biz.service.datacenter.XingTuDataService;
import com.dy.yunying.biz.service.manage.AdRoleUserService;
import com.pig4cloud.pig.admin.api.entity.SysDictItem;
import com.pig4cloud.pig.admin.api.feign.RemoteDictService;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 星图统计接口
 */
@Service
@RequiredArgsConstructor
public class XingTuDataServiceImpl implements XingTuDataService {

	private final AdRoleUserService roleUserService;

	private final XingTuDataDao xingTuDataDao;

	private final ChannelManageDOMapper channelManageDOMapper;

	private final WanGameDOMapper wanGameDOMapper;

	private final WanGameChannelInfoMapper wanGameChannelInfoMapper;

	private final RemoteDictService remoteDictService;

	/**
	 * 星图报表总数
	 *
	 * @param xingtu
	 * @return
	 */
	@Override
	public int count(XingTuDataVO xingtu) {
		this.requireXingtuQueryBean(xingtu);
		if (!xingtu.getIsAdmin() && xingtu.getPrvInvestorIds().isEmpty()) {
			return 0;
		}
		return xingTuDataDao.selectXingtuCount(xingtu);
	}

	/**
	 * 星图报表分页
	 *
	 * @param xingtu 查询条件
	 * @param isPage 是否分页
	 * @return
	 */
	@Override
	public List<XingTuDataDTO> page(XingTuDataVO xingtu, boolean isPage) {
		this.requireXingtuQueryBean(xingtu);
		if (!xingtu.getIsAdmin() && xingtu.getPrvInvestorIds().isEmpty()) {
			return Collections.emptyList();
		}
		final List<XingTuDataDTO> list = xingTuDataDao.selectXingtuPage(xingtu, isPage);
		// 填充主渠道名称和子游戏名称字段
		this.convertXingTuDataList(xingtu, list);
		return list;
	}

	private void requireXingtuQueryBean(XingTuDataVO xingtu) {
		// 判断当前用户是否为系统管理员
		xingtu.setIsAdmin(SecurityUtils.getRoles().contains(1));

		// 当前账号及管理的账号
		if (!xingtu.getIsAdmin()) {
			Set<Long> prvInvestorIds = new HashSet<>();
			prvInvestorIds.add(Integer.toUnsignedLong(SecurityUtils.getUser().getId()));
			prvInvestorIds.addAll(Optional.ofNullable(roleUserService.getOwnerRoleUserIds()).map(Collection::stream).map(e -> e.map(Integer::toUnsignedLong).collect(Collectors.toList())).orElse(Collections.emptyList()));
			xingtu.setPrvInvestorIds(prvInvestorIds);
		}
	}

	private void convertXingTuDataList(XingTuDataVO xingtu, List<XingTuDataDTO> list) {
		final List<String> groupBys = xingtu.getGroupBys();

		// 填充投放方式中文名称
		if (groupBys.contains("settle_type")) {
			final List<SysDictItem> dicList = Optional.ofNullable(remoteDictService.getDictByType4Inner(SecurityConstants.FROM_IN, "kol_type").getData()).orElse(Collections.emptyList());
			if (!dicList.isEmpty()) {
				final Map<String, String> dicMap = dicList.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel, (k1, k2) -> k1));
				list.forEach(e -> e.setSettleName(dicMap.get(e.getSettleType())));
			}
		}

		// 填充主渠道名称
		if (groupBys.contains("parentchl")) {
			final List<String> codeList = list.stream().map(XingTuDataDTO::getParentchl).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
			if (!codeList.isEmpty()) {
				final LambdaQueryWrapper<ChannelManageDO> queryWrapper = Wrappers.<ChannelManageDO>lambdaQuery().select(ChannelManageDO::getChncode, ChannelManageDO::getChnname).in(ChannelManageDO::getChncode, codeList).eq(ChannelManageDO::getPid, 0).eq(ChannelManageDO::getIsdelete, 0);
				final Map<String, String> parentchlMap = channelManageDOMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(ChannelManageDO::getChncode, ChannelManageDO::getChnname, (k1, k2) -> k1));
				list.forEach(e -> e.setParentchlName(parentchlMap.get(e.getParentchl())));
			}
		}

		// 填充分包渠道中文名称
		if (groupBys.contains("appchl")) {
			final List<String> codeList = list.stream().map(XingTuDataDTO::getAppchl).distinct().filter(StringUtils::isNotEmpty).collect(Collectors.toList());
			if (!codeList.isEmpty()) {
				LambdaQueryWrapper<WanGameChannelInfoDO> queryWrapper = Wrappers.<WanGameChannelInfoDO>lambdaQuery().select(WanGameChannelInfoDO::getChl, WanGameChannelInfoDO::getCodeName).in(WanGameChannelInfoDO::getChl, codeList);
				Map<String, String> appchlMap = wanGameChannelInfoMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(WanGameChannelInfoDO::getChl, WanGameChannelInfoDO::getCodeName, (k1, k2) -> k1));
				list.forEach(e -> e.setAppchlName(StringUtils.defaultIfBlank(appchlMap.get(e.getAppchl()), e.getAppchl())));
			} else {
				list.forEach(e -> e.setAppchlName(e.getAppchl()));
			}
		}

		// 填充子游戏名称
		if (groupBys.contains("gameid")) {
			final List<Long> gameidList = list.stream().map(XingTuDataDTO::getGameid).distinct().filter(Objects::nonNull).collect(Collectors.toList());
			if (!gameidList.isEmpty()) {
				final LambdaQueryWrapper<WanGameDO> queryWrapper = Wrappers.<WanGameDO>lambdaQuery().select(WanGameDO::getId, WanGameDO::getGname).in(WanGameDO::getId, gameidList).eq(WanGameDO::getIsdelete, 0);
				final Map<Long, String> gameMap = wanGameDOMapper.selectList(queryWrapper).stream().collect(Collectors.toMap(WanGameDO::getId, WanGameDO::getGname, (k1, k2) -> k1));
				list.forEach(e -> e.setGname(gameMap.get(e.getGameid())));
			}
		}

		// 填充系统名称
		if (groupBys.contains("os")) {
			list.forEach(e -> e.setOsName(OsEnum.getName(e.getOs())));
		}
	}

}
